package hk.hku.hooku.db;

import hk.hku.hooku.pojo.EventChoice;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

public class ContactDB {
	
	public static int getProposerByEmail(String email)
	{
		int proposerid = -1;
		String queryId  = "SELECT id FROM users WHERE gmail=?";
		DBConnector.connect();
		if (DBConnector.getConn() != null){
			try {
				PreparedStatement st = null;
				st = DBConnector.getConn().prepareStatement(
						queryId);
				
				st.setString(1, email);
				ResultSet rs = st.executeQuery();
				if (rs.next()) {
					proposerid = rs.getInt(1);
				}
			}catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		DBConnector.close();
		return proposerid;
	}
	
	public static String getContactByHint(String hint, boolean is_email)
	{
		System.out.println("in getContactByHint");
		String contact_target = null;
		String queryEmail = "SELECT contactEmail FROM contacts WHERE contactName LIKE '?'";
		String queryName  = "SELECT contactName FROM contacts WHERE contactEmail LIKE '?'";
		DBConnector.connect();
		if (DBConnector.getConn() != null){
			try {
				PreparedStatement st = null;
				if(!is_email)
				    st = DBConnector.getConn().prepareStatement(
				    		queryEmail);
				else
					st = DBConnector.getConn().prepareStatement(
							queryName);
				
				st.setString(1, hint);
				ResultSet rs = st.executeQuery();
				if (!rs.next()) {
					return null;
				}
				if(!is_email)
				{
				    contact_target = rs.getString("contactEmail");
				}
				else
				{
					contact_target = rs.getString("contactName");
				}
			}catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		DBConnector.close();
		return contact_target;
	}
	
    public static ArrayList<String> getContactByEmail(String email)
    {
    	ArrayList<String> contactlist = new ArrayList<String>();
    	
		String queryUserId  = "SELECT id FROM users WHERE gmail=?";
		String queryContact = "SELECT contactEmail FROM contacts WHERE userId=?"; 
		DBConnector.connect();
		if (DBConnector.getConn() != null){
			try {
				PreparedStatement st = null;
				st = DBConnector.getConn().prepareStatement(
						queryUserId);
				
				st.setString(1, email);
				ResultSet rs = st.executeQuery();
				if (!rs.next()) {
					DBConnector.close();
					return contactlist;
				}
				
				int userid = rs.getInt("id");
				st = DBConnector.getConn().prepareStatement(
						queryContact);
				
				st.setInt(1, userid);
			    rs = st.executeQuery();
			    while (rs.next()) {
					String cmail = rs.getString("contactEmail");
					contactlist.add(cmail);
				}
			}catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		DBConnector.close();
		return contactlist;
    }
}
